<template>
  <page-view>
    <page-header title="注册" :show-back="true"></page-header>
    <div class="content-box">
      <Form @submit="onSubmit">
        <cell-group inset>
          <field
            v-model="nickname"
            name="昵称"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[{ required: true, message: '请填写昵称' }]"
          />
          <field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <field
            v-model="confirm_password"
            type="password"
            name="重复密码"
            label="重复密码"
            placeholder="请输入密码"
            :rules="[{ validator: validatorPassword }]"
          />
          <field
            type="text"
            v-model="phone"
            label="电话"
            name="电话"
            placeholder="请输入电话"
            :rules="[{ required: true, message: '请填写电话号码' }]"
          />
          <field
            v-model="captcha"
            center
            clearable
            name="验证码"
            label="短信验证码"
            placeholder="请输入短信验证码"
          >
            <template #button>
              <Button size="small" type="primary" @click="sendCaptcha"
                >发送验证码</Button
              >
            </template>
          </field>
        </cell-group>

        <div style="margin: 16px">
          <Button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="正在注册"
            :disabled="loading"
          >
            提交
          </Button>
        </div>
      </Form>
    </div>
  </page-view>
</template>

<script>
import {
  Form,
  Field,
  CellGroup,
  Button,
  RadioGroup,
  Radio,
  Uploader,
  Toast,
} from "vant";
import Api from "../utils/api";
import { useRouter } from "vue-router";
import { reactive, toRefs, ref, getCurrentInstance } from "vue";
export default {
  name: "Register",
  components: {
    Form,
    Field,
    CellGroup,
    Button,
    RadioGroup,
    Radio,
    Uploader,
    Toast,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    let userInfo = reactive({
      captcha: "",
      nickname: "",
      password: "",
      confirm_password: "",
      phone: "",
    });

    //提交按钮 点击提交后 加载状态和禁用状态用loading表示
    let loading = ref(false);

    //校验重复密码
    const validatorPassword = () => {
      if (userInfo.password !== userInfo.confirm_password) {
        return "重复密码不对";
      }
    };

    //表单提交
    const onSubmit = (value) => {
      //收集到所有填的表单数据
      console.log("submit", value);
      // 注册  1.看该手机是否已经注册 没注册的话
      //       2.需要验证码，得发验证码
      //       3.先判断验证码是否正确再进行注册
      addUser();
    };
    //验证手机号，发送验证码
    const sendCaptcha = async () => {
      if (userInfo.phone == "") {
        Toast.fail("请先填写手机号");
        return;
      }

      let results = await Api.User.isRegister(userInfo.phone);
      console.log(results);
      if (results.exist == "1") {
        Toast.fail("改手机号，已经注册，请直接登录");
        router.replace({ name: "Login" });
      } else {
        Toast.success("已发送验证码");
        await Api.User.sendCaptcha(userInfo.phone);
      }
    };
    const addUser = async () => {
      Toast.loading({
        message: "注册中",
        forbidClick: true,
        duration: 0,
      });
      loading.value = true;
      setTimeout(async () => {
        try {
          let results = await Api.User.register(
            userInfo.captcha,
            userInfo.phone,
            userInfo.password,
            userInfo.nickname
          );
          console.log(results);
          Toast.clear(true);
          Toast.success("注册成功");
          router.replace({ name: "Login" });
        } catch (error) {
          console.log(error);
          Toast.fail("注册失败,"+error.response.data.msg);
          if(error.response.data.msg=='该昵称已被占用'){
            //如何让表单的昵称清空？ dom引用？
          }
        } finally {
          loading.value = false;
        }
      }, 2000);
    };

    return {
      ...toRefs(userInfo),
      onSubmit,
      validatorPassword,
      loading,
      sendCaptcha,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>